﻿using System;
using System.Xml;

namespace KouDai.Phone.Helper
{
    public class AppManifest
    {
        private const string AppManifestName = "WMAppManifest.xml";
        private const string AppNodeName = "App";

        private static readonly XmlReaderSettings XmlReaderSettings = new XmlReaderSettings { XmlResolver = new XmlXapResolver() };

        private static string _Author;
        public static string Author
        {
            get { return _Author ?? (_Author = GetAppAttribute("Author")); }
        }

        private static string _Description;
        public static string Description
        {
            get { return _Description ?? (_Description = GetAppAttribute("Description")); }
        }

        private static string _Title;
        public static string Title
        {
            get { return _Title ?? (_Title = GetAppAttribute("Title")); }
        }

        private static string _Version;
        public static string Version
        {
            get { return _Version ?? (_Version = GetAppAttribute("Version")); }
        }

        /// <summary>
        /// Gets an attribute from the Windows Phone App Manifest App element
        /// </summary>
        /// <param name="attributeName">the attribute name</param>
        /// <returns>the attribute value</returns>
        public static string GetAppAttribute(string attributeName)
        {
            using (XmlReader rdr = XmlReader.Create(AppManifestName, XmlReaderSettings))
            {
                rdr.ReadToDescendant(AppNodeName);

                if (!rdr.IsStartElement())
                {
                    throw new System.FormatException(AppManifestName + " is missing " + AppNodeName);
                }
                return rdr.GetAttribute(attributeName);
            }
        }

        public static bool TryGetAppAttribute(string attributeName, out string value)
        {
            try
            {
                value = GetAppAttribute(attributeName);
                return true;
            }
            catch (Exception)
            {
                value = default(string);
                return false;
            }
        }
    }
}
